<template>
  <el-container>
      <el-header class="pdbt rigtop">
        <i class="fa el-icon-s-unfold" @click="clickFold" v-if="iconIf"></i> 
        <i class="fa el-icon-s-fold" @click="clickFold" v-if="!iconIf"></i>
        计算公式信息
      </el-header>
        <el-main class="padding_top heiauto">
          <el-form ref="elForm" :model="formData" :rules="rules" size="mini" label-width="90px" label-position="right">
            <el-form-item label="作用范围" prop="fr" size="mini">
                <el-radio-group v-model="formData.fr"  :disabled='true'>
                <el-radio v-for="(item, index) in fcOptions" :key="index" :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="有效性" prop="fValid" size="mini">
                <el-radio-group v-model="formData.fValid" >
                <el-radio v-for="(item, index) in fValidOptions" :key="index" :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="计算指标"  prop="uuid" size="mini">
              <treeselect   ref="reftree" :default-expand-level="1" :disabled="reftreeDisabled" v-model="formData.uuid" :options="tableIDOptions" :disable-branch-nodes="true" :show-count="true" @select="jszbSelect" placeholder="请选择计算指标" />
                <!--
              <el-select v-model="formData.calCell" placeholder="请选择计算指标" multiple collapse-tags @change="calCellSel">
                  <el-option  :value="mineStatusValue" style="height: auto">
                    <el-tree :data="data" show-checkbox node-key="id" ref="tree" highlight-current :props="defaultProps" @check-change="handleCheckChange"></el-tree>
                </el-option>
              </el-select>
              -->
            </el-form-item>
            <el-row type="flex" justify="center" align="middle" class="el_row_btn">
                <el-form-item label-width="5px" label="" prop="field1">
                <el-button type="primary" size="mini" @click="btnClick('+', '加')">&#43;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field2">
                <el-button type="primary" size="mini" @click="btnClick('-', '减')">&#45;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field3">
                <el-button type="primary" size="mini" @click="btnClick('*', '乘')">&#42;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field4">
                <el-button type="primary" size="mini" @click="btnClick('/', '除')">&#47;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field5">
                <el-button type="primary" size="mini" @click="btnClick('(', '(')">&#40;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field6">
                <el-button type="primary" size="mini" @click="btnClick(')', ')')">&#41;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field7">
                <el-button type="primary" size="mini" @click="btnClick('{', '{')">&#123;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field8">
                <el-button type="primary" size="mini" @click="btnClick('}', '}')">&#125;</el-button>
                </el-form-item>
            </el-row>
            <el-row type="flex" justify="center" align="middle" class="el_row_btn">
                <el-form-item label-width="5px" label="" prop="field9">
                <el-button type="primary" size="mini" @click="btnClick('&&', '与')">&#38;&#38;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field10">
                <el-button type="primary" size="mini" @click="btnClick('||', '或')">&#124;&#124;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field11">
                <el-button type="primary" size="mini" @click="btnClick('>', '大于')">&#62;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field12">
                <el-button type="primary" size="mini" @click="btnClick('>=', '大于等于')">&#62;&#61;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field13">
                <el-button type="primary" size="mini" @click="btnClick('==', '等于')">&#61;&#61;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field14">
                <el-button type="primary" size="mini" @click="btnClick('<', '小于')">&#60;</el-button>
                </el-form-item> <el-form-item label-width="5px" label="" prop="field15">
                  <el-button type="primary" size="mini" @click="btnClick('<=', '小于等于')">&#60;&#61;</el-button>
                </el-form-item>
                <el-form-item label-width="5px" label="" prop="field16">
                <el-button type="primary" size="mini" @click="btnClick('!=', '不等于')">&#33;&#61;</el-button>
                </el-form-item>
            </el-row>
            <el-form-item label-width="0" prop="fc">
                <el-input id="formulaInput" ref="m_input" v-model="formData.fc" type="textarea" :autosize="{minRows: 15, maxRows: undefined}" :style="{width: '100%'}" placeholder="请输入计算公式······"></el-input>
            </el-form-item>
            <el-form-item label-width="0" prop="fd">
                <el-input ref="n_input" v-model="formData.fd" type="textarea" :autosize="{minRows: 8, maxRows: undefined}" :style="{width: '100%'}" placeholder="请输入计算公式说明······"></el-input>
            </el-form-item>
          </el-form>
        </el-main>
        <el-footer style="text-align: center;">
          <el-button size="mini" type="primary" :disabled="dissavebtn" @click="submitForm">保存</el-button>
        </el-footer>
  </el-container>
</template>
<script>
import request from "@/utils/requestutil";
import {getRealUrl, syncRequest} from "@/utils/httpRequet";
import PsTreeSelect from '@/components/psTree/PsTreeSelect';
import treeselect from '@riophae/vue-treeselect'
export default {
  components: {
    request,
    getRealUrl,
    syncRequest,
    PsTreeSelect,
    treeselect,
  },
  props: {
    config: {
      type: Object,
      default: () => {
        return {};
      }
    },
    beforesave: {
      type: Function,
      default: () => {
        return true
      }
    },
    aftersave: {
      type: Function,
      default: () => {
        return false
      }
    },
  },
  data() {
    return {
      iconIf: false,
      reftreeDisabled:false,
      dissavebtn: true,
      formData: {
        bzcode: "",//业务代码
        fc: "",//配置公式
        fd: "",//公式说明
        fr: "IN",//公式范围
        fsord: "",//计算顺序
        fValid: 1,//有效性
        tsCd: "",//索引代码(表单号)
        tsCtm: "",//创建时间
        tsMtm: "",//修改时间
        tsUn: "",//管理单位
        ttId: "",//任务标识
        uuid: undefined,//计算指标
        command: "NEW",
        field1: undefined,
        field2: undefined,
        field3: undefined,
        field4: undefined,
        field5: undefined,
        field6: undefined,
        field7: undefined,
        field8: undefined,
        field9: undefined,
        field10: undefined,
        field11: undefined,
        field12: undefined,
        field13: undefined,
        field14: undefined,
        field15: undefined,
        field16: undefined,
      },
      rules: {
        fc: [],
        // fValid: [{
        //   required: true,
        //   message: '有效性不能为空',
        //   trigger: 'change'
        // }],
        // formula: [{
        //   required: true,
        //   message: '公式不能为空。',
        //   trigger: 'blur'
        // }],
      },
      fcOptions: [{
        "label": "表内",
        "value": 'IN',
      }, {
        "label": "表间",
        "value": 'AMONG',
      }],
      fValidOptions: [{
        "label": "有效",
        "value": 1
      }, {
        "label": "无效",
        "value": 0
      }],
      tableIDOptions: [],
    }
  },
  computed: {},
  watch: {
  },
  created() {},
  mounted() {},
  methods: {
    clickFold() {
          // this.isFold = !this.isFold
          console.log('Before-----'+this.isFold)
          if(this.isFold==='1'){
            this.isFold = '0'
            this.iconIf = false
          }else{
            this.isFold = '1'
            this.iconIf = true
          }
          this.isFoldz = this.isFold
          this.$emit('myclickFold', this.isFoldz)
          console.log('After-----'+this.isFold)
      },
    changeTextarea(innerVl) {
        const dom = this.$refs.m_input.$refs.textarea
        let pos = 0
        let insertText=' ' + innerVl + ' '
        if (dom.selectionStart || dom.selectionStart === 0) {
            pos = dom.selectionStart
            let endPos = dom.selectionEnd
            dom.value = dom.value.substring(0, pos) + insertText + dom.value.substring(endPos, dom.value.length);
            
            //设置选择的起点和终点位置
            dom.dispatchEvent(new Event('input'));
            dom.focus();
            dom.selectionStart = pos + insertText.length;
            dom.selectionEnd = pos + insertText.length;
        }
    },
    setFieldData(filedkey, data) {
      //console.log("控件-左侧菜单传值：", filedkey, data);
      this.$set(this.formData,filedkey,data);
    },
    setData(obj) {
      let data = obj.val
      if(obj.type == "UPDATE") {
        if (data.bzcode) {
          this.formData.bzcode = data.bzcode
        }
        if (data.fc) {
          this.formData.fc = data.fc
        }
        if (data.fd) {
          this.formData.fd = data.fd
        }
        if (data.fr) {
          this.formData.fr = data.fr
        }
        if (data.fsord) {
          this.formData.fsord = data.fsord
        }
        if (data.fValid) {
          this.formData.fValid = parseInt(data.fValid)
        }
        if (data.tsCd) {
          this.formData.tsCd = data.tsCd
        }
        if (data.tsCtm) {
          this.formData.tsCtm = data.tsCtm
        }
        if (data.tsMtm) {
          this.formData.tsMtm = data.tsMtm
        }
        if (data.tsUn) {
          this.formData.tsUn = data.tsUn
        }
        if (data.ttId) {
          this.formData.ttId = data.ttId
        }
        if (data.uuid) {
          this.formData.uuid = data.uuid
        } else {
          this.formData.uuid = undefined
        }
        this.formData.command = "UPDATE"

        this.tableIDOptions = [{"id": data.uuid,"label": data.tiCdNnm}]
        this.reftreeDisabled=true
      } else {
        this.reftreeDisabled=false
        this.formData.command = data.command
      }
      this.dissavebtn = false
    },
    clearAll() {
      this.formData={bzcode: "",fc: "",fd: "",fr: "",fsord: "",fValid: 1,tsCd: "",tsCtm: "",tsMtm: "",tsUn: "",ttId: "",uuid: undefined,command: "NEW",field1: undefined,field2: undefined,field3: undefined,field4: undefined,field5: undefined,field6: undefined,field7: undefined,field8: undefined,field9: undefined,field10: undefined,field11: undefined,field12: undefined,field13: undefined,field14: undefined,field15: undefined,field16: undefined,}
      this.dissavebtn = true
    },
    resetForm(obj) {
      this.$refs.m_input.$refs.textarea.value = "";
      this.$refs.n_input.$refs.textarea.value = "";

      this.formData.bzcode = obj.val.bzcode
      this.formData.fc = obj.val.fc
      this.formData.fd = obj.val.fd
      this.formData.fr = obj.val.fr
      this.formData.fsord = obj.val.fsord
      this.formData.fValid = obj.val.fValid
      this.formData.tsCd = obj.val.tsCd
      this.formData.tsCtm = obj.val.tsCtm
      this.formData.tsMtm = obj.val.tsMtm
      this.formData.tsUn = obj.val.tsUn
      this.formData.ttId = obj.val.ttId
      this.formData.uuid = obj.val.uuid
      this.formData.command = obj.val.command
      this.reftreeDisabled=false
      this.refreshTreeOptions()
      
      this.dissavebtn = false
    },
    handleNodeClick(val) {
      //console.log(val);
    },
    calCellSel(selVal) {
      //console.log(selVal);
      this.changeTextarea(selVal)
    },
    btnClick(val) {
      this.changeTextarea(val);
        //this.changeTextarea(obj.currentTarget.outerText);
        //  if ("+" == btnNM) {
        //  } else if ("-" == btnNM) {
        //  } else if ("*" == btnNM) {
        //  } else if ("/" == btnNM) {
        //  } else if ("(" == btnNM) {
        //  } else if (")" == btnNM) {
        //  } else if ("{" == btnNM) {
        //  } else if ("}" == btnNM) {
        //  } else if ("&&" == btnNM) {
        //  } else if ("||" == btnNM) {
        //  } else if (">" == btnNM) {
        //  } else if (">=" == btnNM) {
        //  } else if ("==" == btnNM) {
        //  } else if ("<" == btnNM) {
        //  } else if ("<=" == btnNM) {
        //  } else if ("!=" == btnNM) {
        //  }
    },
    submitForm() {
      //console.log(document.getElementById("formulaInput").selectionStart);
      if (!this.formData.command || this.formData.command == "") {
        this.formData.command = "NEW"
      }
      const $t = this
      this._getData().then((data) => {
        if ($t.beforesave) {
          var s = $t.beforesave(data)
          if (s === false) return
        }
        if (!this.formData.uuid || this.formData.uuid==undefined || this.formData.uuid=="undefined") {
          $t.$message.warning("请选择计算指标");
          return 
        }
        let aurl = "dcbjs_edit"
        console.log("控件保存：",aurl,$t.formData);
        if (this.formData.command == 'NEW') {
          this.formData.tsUn=nullToSpace(this.$store.state.user.userInfo.deptId)
          this.formData.tsCtm=new Date().Format("yyyy-MM-dd hh:mm:ss")
        }
        this.formData.tsMtm=new Date().Format("yyyy-MM-dd hh:mm:ss")
        request({
          url: aurl,
          method: 'post',
          params: $t.formData,
        }).then((res) => {
          if(res.errorCode=='1'){
            $t.$message.success('保存成功')
            $t.dissavebtn = true
          }else if(res.errorCode<0){
            this.$message({type:'error',message:"保存失败"});
          }
          let _data = data //保存后的data
          var s = $t.aftersave(_data, data)
          if (s === false) return
        })
      })
    },
    refreshTreeOptions() {
      //console.log("refreshTreeOptions:", this.formData);
      if (this.formData && this.formData.bzcode && this.formData.ttId) {
        request({
          url:'dcbjs_zszb_sel',
          method:'post',
          data:{ywValue:this.formData.bzcode,rwValue:this.formData.ttId,tsCd: this.formData.tsCd,command:this.formData.command},
        }).then(data=>{
          //console.log("计算右侧下拉树：",data.data);
          this.tableIDOptions = eval(data.data)
        })
      }
    },
    datafilter(treeid,pnode,resdata){
        if(resdata && resdata.data&& resdata.data.length>0){
          let _val=t.value?t.value.split(","):[];
          let resault=[];
          t.$_.forEach(resdata.data,(item,i)=>{
            // item.name=item.text;
            // item.pid=item.fid;
            // item.isParent=true;
              if(item.leaf=='0')item.isParent=true
              else if(item.leaf=='1' && this.searchtext){
                if(item.name.indexOf(this.searchtext)==-1)return;
              }
            resault.push(item);
          })
        }else{
          if(pnode)
          pnode.isParent=false;
        }
          return resault;
    },
    dealTreaparam(treeid,node){
      if(node==undefined){
        return {p0:'root',p1:'1'}
      }else{
        return {p0:node.id,p1:'1'};
      }
    },
    async _getData() {
      return await this.formData
    },
    jszbSelect(value, instanceId) {
      this.formData.ttId = value.ttId
      this.formData.tsCd = value.tsCd
    },
  }
}
function nullToSpace (str) {
  if(!str || str=="undefined" || str=="null"){
    return "";
  }
  return str + "";
}
Date.prototype.Format = function(fmt) { 
     var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
    }; 
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
}
</script>
<style lang="scss" scoped>
.padding_top .el-form{
  padding: 0 10px;
}

.el_row_btn .el-button--mini{
  padding:4px 6px;
  width:100%;
}
.padding_top .el_row_btn .el-form-item{
  margin-bottom: 0px;
  flex: 1;
  margin-top:0;
}
.padding_top .el-form-item{
  margin-top: 8px;
  margin-bottom: 8px;
}
.padding_top .el-textarea{
  margin-top: 8px;
  margin-bottom: 8px;
}
::v-deep .el-form-item--medium .el-form-item__label{
  text-align: right;
}
::v-deep .padding_top .el-form-item--medium .el-form-item__content{
  line-height: 30px; text-align: left;
}
</style>
